import React, { memo, useEffect, useMemo, useState } from 'react'
import classNames from 'classnames'
import './style.less'
import { Button, Flex, Space, Tag } from 'antd'
import { HsAdminInput, HsAdminSelect, HsAdminSpin, HsAdminTablePage } from '@hs-admin/base-components'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { reqTopicList } from '@/api/dataMarket' // 接口
import { EMPTYTEXT, message, usePage } from '@hs-admin/utils'
import { getDataCollectProductDataItemList } from '@/api/assetMaintain/dataProduct'
import { handleButtonShow } from '@/utils/tools'
import { useImmer } from 'use-immer'
import { reqDataItemList } from '@/api/assetMaintain/basic/item'
import { dataItemSettingType } from '@/utils/type'
import { HsAdminDataItemDetailModal } from '@hs-admin/components'
import { addItemsToCart } from '@/views/ShoppingCart/commonProps.ts'

const ThemeDetail: React.FC = () => {
  const [searchParams]: any = useSearchParams()
  const [choseTopicId, setchoseTopicId] = useState(searchParams.get('id')) // 选择的主题id
  const [choseTopicName, setchoseTopicName] = useState('')
  const [choseTopicDes, setchoseTopicDes] = useState('')
  const [topicList, settopicList] = useState<any[]>([])
  const [searchValue, setsearchValue] = useState<string>('')
  const { pagination, resetPage, initPage } = usePage(getDataItemList)
  const [dataItemId, setdataItemId] = useState('')

  const columns: any[] = [
    {
      title: '数据项名称',
      dataIndex: 'name'
    },
    {
      title: '英文表名',
      dataIndex: 'ref_table_name'
    },
    {
      title: '数据项描述',
      dataIndex: 'description',
      ellipsis: true
    },
    {
      title: '支持筛选维度',
      dataIndex: 'specifications',
      render: (_: any, record: { specifications: any[] }) => {
        let specificationsTypeList = record.specifications.map((item: { type: any }) => item.type)
        const specificationsTypeSet = new Set(specificationsTypeList)
        specificationsTypeList = [...specificationsTypeSet]
        const name = specificationsTypeList.map((item) => dataItemSettingType(item)).join('、')
        return <span>{name || EMPTYTEXT}</span>
      }
    },
    {
      title: '所属主题',
      dataIndex: 'data_topics',
      render: (_: any, record: { data_topics: any[] }) => {
        const name = record.data_topics.map((item: { name: any }) => item.name).join('、')
        return <span>{name}</span>
      }
    },
    {
      title: '数据特征',
      dataIndex: 'data_characteristics',
      render: (_: any, record: { data_characteristics: string[] }) => (
        <>
          {record.data_characteristics?.map((tagKey) => (
            <Tag style={{ marginRight: '6px' }} bordered={false} color="processing" key={tagKey}>
              {tagKey}
            </Tag>
          ))}
          {!record.data_characteristics?.length && <span>{EMPTYTEXT}</span>}
        </>
      )
    },
    {
      title: '数据项量',
      dataIndex: 'itemCount'
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (_: any, record: any) => (
        <>
          <Button type="link" size="small" onClick={() => handleGoDetail(record)}>
            详情
          </Button>
        </>
      )
    }
  ]
  const [data, setdata] = useState<any[]>([])
  const navigate: any = useNavigate()
  const source = searchParams.get('source')
  const [data_characteristic, setdata_characteristic] = useState(undefined)
  const [specification_types, setspecification_types] = useState([])
  const typeOptions = useMemo(
    () => [
      {
        label: '热门数据',
        value: '热门数据'
      },
      {
        label: '特色数据',
        value: '特色数据'
      }
    ],
    []
  )
  const [loading, setloading] = useState(true)

  const [shopping, setShopping] = useState(false)

  // 获取数据-主题列表
  const getTopicList = async () => {
    const res = await reqTopicList({ status: 'published' })
    res.items.unshift({ name: '全部', id: null })
    settopicList(res.items)
    const findItem = res.items.find((item: any) => item.id === choseTopicId)
    setchoseTopicName(findItem?.name)
    setchoseTopicDes(findItem?.description)
  }
  // 主题点击
  const handleTopicClick = (item: any) => {
    setchoseTopicId(item.id)
    setchoseTopicName(item.name)
    setchoseTopicDes(item.description)
    resetPage()
  }
  const getBasicDataItemList = async () => {
    setloading(true)
    setdata([])
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      data_topic_id: choseTopicId,
      keywords: searchValue || undefined,
      data_characteristics: data_characteristic,
      specification_types: specification_types.join(','),
      status: 'published'
    }
    const res = await reqDataItemList(params)
    // 格式化列表
    const dataList = res.items.map((element: { data_characteristics: any[]; data_count: number }) => ({
      ...element,
      data_characteristics: element.data_characteristics.filter((item: string[]) => item),
      itemCount: element.data_count
        ? element.data_count >= 10000
          ? (element.data_count / 10000).toFixed(2) + ' 万条'
          : element.data_count + ' 条'
        : ''
    }))
    setdata(dataList)
    setloading(false)
    return res
  }
  // 数据产品获取列表
  const callDataProductItemList = async () => {
    setloading(true)
    setdata([])
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      id: searchParams.get('id'),
      keywords: searchValue,
      data_characteristic
    }
    const res = await getDataCollectProductDataItemList(params)
    // 格式化列表
    const dataList = res.items.map((element: { data_count: number }) => ({
      ...element,
      itemCount: element.data_count >= 10000 ? (element.data_count / 10000).toFixed(2) + ' 万条' : element.data_count + ' 条'
    }))
    setdata(dataList)
    setloading(false)
    return res
  }
  // 获取数据-数据项列表
  async function getDataItemList() {
    if (!source) {
      return getBasicDataItemList()
    } else {
      return callDataProductItemList()
    }
  }
  // 去详情
  const handleGoDetail = (record: any) => {
    setdataItemId(record.id)
  }
  // 搜索按钮
  const handleSearchClick = () => {
    initPage()
    getDataItemList()
  }
  const openDemandOrder = () => {
    const url = `/dataService?newOrder=true&order_type=基础数据订单`
    window.open(url, '_blank')
  }
  const openShoppingCart = () => {
    setShopping(true)
    addItemsToCart(selectedData.map((it) => it.id))
      .then(() => {
        navigate('/shoppingCart')
      })
      .catch(() => {
        message.error('加购失败')
      })
      .finally(() => {
        setShopping(false)
      })
  }

  const [selectedRowKeys, setselectedRowKeys] = useImmer<any[]>([])
  const [selectedData, setselectedData] = useImmer<any[]>([])
  const rowSelection = {
    onSelect: (record: any, selected: boolean) => {
      if (selected) {
        setselectedRowKeys((prevState) => {
          prevState.push(record.id)
        })
        setselectedData((prevState) => {
          prevState.push(record)
        })
      } else {
        setselectedRowKeys((prevState) => {
          const index = prevState.findIndex((ele) => ele === record.id)
          prevState.splice(index, 1)
        })
        setselectedData((prevState) => {
          const index = prevState.findIndex((ele) => ele.id === record.id)
          prevState.splice(index, 1)
        })
      }
    },
    onSelectAll: (selected: boolean, _selectedRows: any[], changeRows: any[]) => {
      if (selected) {
        setselectedRowKeys((prevState) => {
          const ids = changeRows.map((item: any) => item.id)
          prevState = [...prevState, ...ids]
          return prevState
        })
        setselectedData((prevState) => {
          prevState = [...prevState, ...changeRows]
          return prevState
        })
      } else {
        setselectedRowKeys((prevState) => {
          const ids = changeRows.map((item: any) => item.id)
          ids.forEach((item: string) => {
            const index = prevState.findIndex((ele) => ele === item)
            prevState.splice(index, 1)
          })
        })
        setselectedData((prevState) => {
          changeRows.forEach((ele: any) => {
            const index = prevState.findIndex((item) => item.id === ele.id)
            prevState.splice(index, 1)
          })
        })
      }
    }
  }

  useEffect(() => {
    if (!source) {
      getTopicList()
    } else {
      setchoseTopicName(searchParams.get('name'))
      setchoseTopicDes(searchParams.get('description'))
    }
  }, [])

  return (
    <div className="themeDetail">
      {loading && <HsAdminSpin />}
      {!source && (
        <div className="top">
          {topicList.map((item, index) => (
            <div className={classNames('top_item', { isActive: item.id === choseTopicId })} key={index} onClick={() => handleTopicClick(item)}>
              {item.name}
            </div>
          ))}
        </div>
      )}

      <div className="mid">
        <div className="mid_title">
          <div>{choseTopicName}</div>
          <Space align="center">
            {!source && handleButtonShow('datashop.demand_order.create') && (
              <Button type="primary" onClick={openDemandOrder}>
                去下单
              </Button>
            )}
            <Button type="primary" loading={shopping} disabled={!selectedData?.length} onClick={openShoppingCart}>
              {shopping ? '加购中' : '加入购物车'}
            </Button>
          </Space>
        </div>

        <div className="my-4 break-words">{choseTopicDes}</div>

        <Flex align="center" gap={'middle'}>
          <Flex align="center" gap={'small'}>
            <span className="flex-none">包含数据项：</span>
            <HsAdminInput
              defaultValue={searchValue}
              placeholder="请输入数据项名称、英文表名"
              allowClear
              onChange={(e: { target: { value: React.SetStateAction<string> } }) => setsearchValue(e.target.value)}
              className="min-w-md"
              onPressEnter={(e: { target: { value: React.SetStateAction<string> } }) => {
                setsearchValue(e.target.value)
                handleSearchClick()
              }}
            />
            <Button type="primary" onClick={handleSearchClick}>
              搜索
            </Button>
          </Flex>
          {!source && (
            <>
              <Flex align="center">
                <span>支持筛选维度：</span>
                <HsAdminSelect
                  defaultValue={specification_types}
                  options={dataItemSettingType()}
                  placeholder="请选择支持筛选维度"
                  allowClear
                  mode="multiple"
                  className="w-60"
                  onChange={(value: React.SetStateAction<never[]>) => {
                    setspecification_types(value)
                    resetPage()
                  }}
                />
              </Flex>
              <Flex align="center">
                <span>数据特征：</span>
                <HsAdminSelect
                  defaultValue={data_characteristic}
                  options={typeOptions}
                  placeholder="请选择数据特征"
                  allowClear
                  className="w-60"
                  onChange={(value: React.SetStateAction<undefined>) => {
                    setdata_characteristic(value)
                    resetPage()
                  }}
                />
              </Flex>
            </>
          )}
        </Flex>
        <br />
        <HsAdminTablePage
          id="J_theme_detail_view"
          columns={columns}
          rowKey="id"
          dataSource={data}
          pagination={pagination}
          rowSelection={{ selectedRowKeys, ...rowSelection }}
          size="small"
        />
      </div>
      <HsAdminDataItemDetailModal id={dataItemId} onCancel={() => setdataItemId('')} />
    </div>
  )
}

export default memo(ThemeDetail)
